package com.hospital.hms.service.impl;

import cn.hutool.core.map.MapUtil;
import com.hospital.hms.exception.GlobalException;
import com.hospital.hms.utils.PageUtils;
import com.hospital.hms.dao.mapper.MedicalDeptDao;
import com.hospital.hms.pojo.MedicalDept;
import com.hospital.hms.service.MedicalDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class MedicalDeptServiceimpl implements MedicalDeptService {
    @Autowired
    MedicalDeptDao medicalDeptDao;

    @Override
    public PageUtils selectConditionByPage(Map<String,Object> map) {
        long count = medicalDeptDao.selectConditionByPageCount(map);
        if (count==0){
            return new PageUtils(Collections.emptyList(),count,MapUtil.getInt(map,"page"),MapUtil.getInt(map,"length"));
        }else {
            return new PageUtils(medicalDeptDao.selectConditionByPage(map),
                    count, MapUtil.getInt(map,"page"),MapUtil.getInt(map,"length"));
        }


    }

    @Override

    public HashMap selectById(int id) {
        return medicalDeptDao.selectById(id);
    }

    @Override
    @Transactional
    public void update(MedicalDept medicalDept) {
        medicalDeptDao.update(medicalDept);

    }




    @Override
    @Transactional
    public void deleteByIds(Integer[] ids) {

        long count = medicalDeptDao.selectSubCountByIds(ids);
        if (count==0){
            medicalDeptDao.deleteByIds(ids);
        }else {

            throw new GlobalException("科室存在关联诊室，无法删除记录");

        }

    }

    @Override
    @Transactional
    public void insert(MedicalDept entity) {
        medicalDeptDao.insert(entity);
    }
    @Override
    public ArrayList<HashMap> selectAllDeptNameAndId() {
        return medicalDeptDao.selectAllDeptNameAndId();
    }

    @Override
    public LinkedHashMap<String, ArrayList<HashMap<String, Object>>> selectDeptAndSub() {
        ArrayList<HashMap> list = medicalDeptDao.selectDeptAndSub();
        //构造结果集
        LinkedHashMap<String, ArrayList<HashMap<String, Object>>> map = new LinkedHashMap<>();
        for (HashMap hashMap : list) {
            String deptName = (String)hashMap.get("deptName");
            String subName = (String)hashMap.get("subName");
            Integer subId = (Integer) hashMap.get("subId");
            map.computeIfAbsent(deptName,key -> new ArrayList<>()).add(new HashMap<>(){{
                put("subId",subId);
                put("subName",subName);

            }});
        }
        return map;
    }
}
